﻿using System;
using System.Diagnostics;
using System.Threading;
using Core.Common;

namespace ThreadingTest
{
    class Program
    {
        private static Stopwatch watch;  
        private static System.Threading.Timer timer;

        [STAThread]
        static void Main(string[] args)
        {
            watch = new Stopwatch();
            TimeoutHelper timeout = new TimeoutHelper();
            timeout.Do = new Program().DoSomething;
            watch.Start();
            timer = new System.Threading.Timer(timerCallBack, null, 0, 500);
            Console.WriteLine("4秒超时开始执行");
            bool bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 4));
            Console.WriteLine(string.Format("4秒超时执行结果,是否超时：{0}", bo));
            Console.WriteLine("***************************************************");

            timeout = new TimeoutHelper();
            timeout.Do = new Program().DoSomething;
            Console.WriteLine("6秒超时开始执行");
            bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 6));
            Console.WriteLine(string.Format("6秒超时执行结果,是否超时：{0}", bo));

            timerCallBack(null);

            watch.Stop();
            timer.Dispose();
            Console.ReadLine();
        }
        static void timerCallBack(object obj)
        {
            Console.WriteLine(string.Format("运行时间:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2")));
        }
        public void DoSomething()
        {
            // 休眠 5秒  
            System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 5));
        }  
    }
}
